#include "variable.h"

variable *variable_new()
{
    variable *var = (variable *)malloc(sizeof(variable));
    var->name = str_new();
    var->value = str_new();
    return var;
}

void variable_delete(void *var)
{
    variable *v = (variable *)var;
    str_delete(v->name);
    str_delete(v->value);
    free(v);
}

void variable_add(string *name, string *value)
{
    variable *var = variable_new();
    str_cat(var->name, name);
    if(value != NULL) str_cat(var->value, value);
    ll_insert_last(variable_list, var);
}

string *variable_get(string *name)
{
    char *str = str_to_array(name);
    char *env = getenv(str);
    string *value = str_new();
    ll_iterator *it;
    variable *var;

    if(env != NULL)
    {
        str_cats(value, env);
    }
    else
    {
        it = ll_get_iterator(variable_list);
        while(!ll_is_end(it))
        {
            var = (variable *)ll_get(it);
            if(str_equal(name, var->name))
            {
                str_cat(value, var->value);
                break;
            }
            ll_next(it);
        }
        free(it);
    }

    free(str);
    return value;
}
